package org.kiwi.data.util;

import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang3.ArrayUtils;
import org.kiwi.data.annotation.Param;
import org.springframework.aop.support.AopUtils;
import org.springframework.core.BridgeMethodResolver;
import org.springframework.util.ClassUtils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by jack on 16/10/19.
 */
public class MethodUtil {

    public static Method getRealMethod(MethodInvocation invocation) {
        Class<?> targetClass = AopUtils.getTargetClass(invocation.getThis());
        Method specificMethod = ClassUtils.getMostSpecificMethod(invocation.getMethod(), targetClass);
        specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
        return specificMethod;
    }

    public static String[] getParameterNames(Method method) {
        List<String> paramNameList = new ArrayList<>();
        Annotation[][] methodParameterAnnotations = method.getParameterAnnotations();
        if (ArrayUtils.isNotEmpty(methodParameterAnnotations)) {
            for (Annotation[] annotations : methodParameterAnnotations) {
                if (ArrayUtils.isNotEmpty(annotations)) {
                    for (Annotation annotation : annotations) {
                        if (annotation instanceof Param) {
                            paramNameList.add(((Param) annotation).value());
                            break;
                        }
                    }
                }
            }
        }
        String[] paramNames = new String[paramNameList.size()];
        return paramNameList.toArray(paramNames);
    }
}
